package com.enjoy.xbase.qk;

import com.enjoy.xbase.qk.impi.DataProcessor;
import com.enjoy.xbase.qk.impi.ISSLManage;
import com.enjoy.xbase.qk.impi.RequestBack;
import com.enjoy.xbase.qk.impi.RequestInfo;
import com.enjoy.xbase.qk.impi.RequestManger;
import com.enjoy.xbase.qk.model.CommonModel;
import com.enjoy.xbase.qk.task.DeleteTask;
import com.enjoy.xbase.qk.task.GetTask;
import com.enjoy.xbase.qk.task.PostTask;
import com.enjoy.xbase.qk.task.PutTask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.CookieJar;
import okhttp3.OkHttpClient;

/**
 * Created by cxb on 2017/12/13.
 */

public class TaskManger implements RequestInfo, RequestManger {

    private static RequestManger instance;

    //请求标识
    private HashMap<String, Long> requestTags = new HashMap<>();

    //前置数据处理器
    private DataProcessor dataProcessor;

    private CookieJar cookieJar;
    private ISSLManage sslManage;

    private List<Call> calls = new ArrayList<>();

    //call 变化锁
    private String callLock = "9527001209";


    /**
     * 描述：初始化
     * @param cookieJar
     * @param dataProcessor 全局数据拦截器
     * @param sslManage
     */
    public static void init(CookieJar cookieJar, DataProcessor dataProcessor, ISSLManage sslManage) {
        instance = new TaskManger(dataProcessor, cookieJar, sslManage);
    }

    /*构造器*/
    private TaskManger(DataProcessor dataProcessor, CookieJar cookieJar, ISSLManage sslManage) {
        this.dataProcessor = dataProcessor;
        this.cookieJar = cookieJar;
        this.sslManage = sslManage;
    }



    public static RequestManger getInstance() {
        if (instance == null)
            throw new RuntimeException("TaskManger未初始化话,请初始化后在使用");
        return instance;
    }

    public void request(CommonModel commonModel, RequestBack back) {
        if (this.dataProcessor != null)
            this.dataProcessor.sendProcess(commonModel);
        if (commonModel.getTag() != null) {
            requestTags.put(commonModel.getTag(), commonModel.getRequestTime());
        }
        if (commonModel.getMethod() == CommonModel.Method.GET) {
            new Thread(new GetTask(commonModel, back, this)).start();
        } else if (commonModel.getMethod() == CommonModel.Method.POST) {
            new Thread(new PostTask(commonModel, back, this)).start();
        } else if (commonModel.getMethod() == CommonModel.Method.DELETE) {
            new Thread(new DeleteTask(commonModel, back, this)).start();
        } else if (commonModel.getMethod() == CommonModel.Method.PUT) {
            new Thread(new PutTask(commonModel, back, this)).start();
        }
    }

    /**
     * 描述：只是判断不移除
     *
     * @param tag
     * @param time
     * @return
     */
    @Override
    public boolean isLast(String tag, long time) {
        if (tag == null || tag.equals("")) {
            return true;
        } else {
            Long saveTime = requestTags.get(tag);
            return saveTime != null && saveTime == time;
        }
    }

    /**
     * 判断：如果是最后一次并移除
     *
     * @param tag
     * @param time
     * @return
     */
    @Override
    public boolean isLastRemove(String tag, long time) {
        if (tag == null || tag.equals("")) {
            return true;
        } else {
            Long saveTime = requestTags.get(tag);
            if (saveTime != null && saveTime == time) {
                requestTags.remove(tag);
                return true;
            } else {
                return false;
            }
        }
    }

    public void addCall(Call call) {
        synchronized (callLock) {
            calls.add(call);
        }
    }

    public void removeCall(Call call) {
        synchronized (callLock) {
            calls.remove(call);
        }
    }

    public void cancelCall(String tagId) {
        synchronized (callLock) {
            for (int i = 0; i < calls.size(); i++) {
                Call call = calls.get(i);
                if (call.request().tag().equals(tagId)) {
                    call.cancel();
                }
            }
        }
    }

    @Override
    public void cancelAllCall() {
        synchronized (callLock) {
            for (int i = 0; i < calls.size(); i++) {
                Call call = calls.get(i);
                call.cancel();
            }
        }
    }

    @Override
    public DataProcessor getDataProcessor() {
        return this.dataProcessor;
    }

    @Override
    public synchronized OkHttpClient getClient() {
        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        httpBuilder.readTimeout(70, TimeUnit.SECONDS)
                .connectTimeout(70, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS);//设置超时
        if (sslManage != null) {//配置请求证书
            httpBuilder.sslSocketFactory(sslManage.getSSLSocketFactory());
            httpBuilder.hostnameVerifier(sslManage.getHostnameVerifier());
        }
        if (cookieJar != null) {
            httpBuilder.cookieJar(cookieJar);
        }
        return httpBuilder.build();
    }

    public synchronized OkHttpClient getUpFileClient() {
        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        httpBuilder.readTimeout(70, TimeUnit.SECONDS)
                .connectTimeout(70, TimeUnit.SECONDS)
                .writeTimeout(360, TimeUnit.SECONDS);//设置超时
        if (sslManage != null) {//配置请求证书
            httpBuilder.sslSocketFactory(sslManage.getSSLSocketFactory());
            httpBuilder.hostnameVerifier(sslManage.getHostnameVerifier());
        }
        if (cookieJar != null) {
            httpBuilder.cookieJar(cookieJar);
        }
        return httpBuilder.build();
    }


}
